package aod.android.com.bernay.mine.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import aod.android.com.bernay.R;
import aod.android.com.bernay.base.BernayBaseActivity;
import aod.android.com.bernay.base.ConstValue;
import aod.android.com.bernay.http.BernayApi;
import aod.android.com.bernay.http.BernayCallback;
import aod.android.com.bernay.live.activity.AddLiveActivity;
import aod.android.com.bernay.live.until.ImageUpdata;
import aod.android.com.bernay.loginandregister.LoginActivity;
import aod.android.com.bernay.loginandregister.bean.UserDataBean;
import aod.android.com.bernay.mine.module.MineUserInfo;
import aod.android.com.bernay.util.SharePreUtils;
import aod.android.com.bernay.util.Utils;
import aod.android.com.bernay.view.ActionSheetDialog;
import chen.lion.hilib.util.LogUtils;
import chen.lion.hilib.view.bind.HiView;

/**
 * @author crated by zhixianuanyang on 2019/4/3 13:15
 * @Email jamesKing0812@gmail.com
 */
public class SettingActivity extends BernayBaseActivity  implements View.OnClickListener{

    @HiView(R.id.iv_headPortrait)
    private ImageView mHeadPortrait;

    @HiView(R.id.tv_nickName)
    private TextView mNickName;

    @HiView(R.id.tv_bindphone)
    private TextView mBindphone;

    @HiView(R.id.tv_realName)
    private TextView mRealName;

    @HiView(R.id.rl_portrait)
    private RelativeLayout layoutPortrait;

    @HiView(R.id.rl_nickName)
    private RelativeLayout layoutNickName;

    @HiView(R.id.rl_realName)
    private RelativeLayout layoutRealName;

    @HiView(R.id.rl_cellphone)
    private RelativeLayout layoutCellphone;

    @HiView(R.id.rl_changePassword)
    private RelativeLayout layoutPassword;

    @HiView(R.id.rl_logout)
    private RelativeLayout layoutLogout;

    private ImageUpdata imageUpdata;
    private MineUserInfo  mineUserInfo;//个人信息
    private RequestOptions requestOptions; //glide加载样式修改
    private int maxSelectNum = 1;//图片选择数量
    private int themeId;//选择图片框样式
    private String alreadyUpload = ""; //已上传图片
    private String selectType = "1";//空为未选择，1为选择照片，2为选择视频
    private List<LocalMedia> selectList = new ArrayList<>();//选择图片数组
    private List<String> qiniuImageUrl = null;//上传七牛文件地址
    private StringBuffer uploadFile = new StringBuffer();//七牛返回的图片文件名称

    @Override
    protected int initLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initData() {
        initTitle(getString(R.string.personal_data));
        initClick();
        themeId = R.style.picture_default_style;
        requestOptions = RequestOptions.circleCropTransform()
                .placeholder(R.drawable.icon_head_portrait)
                .error(R.drawable.icon_head_portrait)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                .skipMemoryCache(true);
        getUserInfo();
    }

    //初始化点击事件
    private void initClick() {
        layoutLogout.setOnClickListener(this);
        layoutPortrait.setOnClickListener(this);
        layoutNickName.setOnClickListener(this);
        layoutRealName.setOnClickListener(this);
        layoutCellphone.setOnClickListener(this);
        layoutPassword.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle();
        switch (v.getId()){
            case R.id.rl_portrait:
                uplodaHeadImage();
                break;
            case R.id.rl_nickName:
                bundle.putString("title","修改昵称");
                goActivity(ModifyPersonalActivity.class,bundle);
                break;
            case R.id.rl_realName:
                bundle.putString("title","修改真实姓名");
                goActivity(ModifyPersonalActivity.class,bundle);
                break;
            case R.id.rl_cellphone:
                Utils.callPhone(this,mBindphone.getText().toString());
                break;
            case R.id.rl_changePassword:
                bundle.putString("loginName",mineUserInfo.getData().get(0).getLogName());
                goActivity(PasswordActivity.class,bundle);
                break;
            case R.id.rl_logout:
                goActivity(LoginActivity.class,bundle);
                break;
            default:
                break;
        }
    }

    public void uplodaHeadImage(){
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                openAlbum();
                            }
                        })
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                openCamera();
                            }
                        }).show();
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        PictureSelector.create(SettingActivity.this).openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(maxSelectNum)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .enablePreviewAudio(false) // 是否可播放音频
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .isCamera(false)
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 false : tru
                .videoMaxSecond(15).videoMinSecond(10)
                .cropCompressQuality(80)// 裁剪压缩质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(SettingActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    updateHeadPortrait(PictureSelector.obtainMultipleResult(data));
                    break;
            }
        }
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo(){
        String userId = SharePreUtils.newInstance(SettingActivity.this).getUserId();
        String token =  SharePreUtils.newInstance(SettingActivity.this).getToken();
        BernayApi.http().getUserInfo(userId, token,new BernayCallback() {
            @Override
            public void onJsonData(String json) {
                mineUserInfo = new Gson().fromJson(json, MineUserInfo.class);
                if (1 == mineUserInfo.getStatus()){
                   String url =  mineUserInfo.getData().get(0).getHeadPicUrl().replace("\\","");
                    Glide.with(SettingActivity.this)
                            .load(url)
                            .apply(requestOptions)
                            .into(mHeadPortrait);
                    mNickName.setText(mineUserInfo.getData().get(0).getNickName());
                    mBindphone.setText(mineUserInfo.getData().get(0).getTel());
                    mRealName.setText(mineUserInfo.getData().get(0).getRealName());
                }
            }

            @Override
            public void onHttpFailure(IOException e) {
                LogUtils.json(new Gson().toJson(e));
            }
        });
    }

    protected void updateHeadPortrait(List<LocalMedia> list){
        qiniuImageUrl = new ArrayList<>();
        for (LocalMedia media : list) {
            qiniuImageUrl.add(media.getPath());
        }

        imageUpdata = new ImageUpdata(this, selectType, qiniuImageUrl, new ImageUpdata.BackFileNameListener() {
            @Override
            public void onBackFileName(List<String> uplodaFileDatas) {
                for (String str : uplodaFileDatas) {
                    if (selectType.equals("1")) {
                        uploadFile.append(str + ".jpg");//上传图片
                    }
                }
                if(selectType.equals("1")){
                    alreadyUpload =  uploadFile.toString();
                }
                String userId = SharePreUtils.newInstance(SettingActivity.this).getUserId();
                String token = SharePreUtils.newInstance(SettingActivity.this).getToken();
                BernayApi.http().saveUserHead(userId,token, ConstValue.QINIU_IMAGE_URL+alreadyUpload,new BernayCallback() {
                    @Override
                    public void onJsonData(String json) {
                        showToast("头像上传成功");
                    }

                    @Override
                    public void onHttpFailure(IOException e) {
                        showToast("头像上传失败");
                    }
                });
            }
        });
    }



    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
